package core

import (
	"log/slog"
	"os"
	"path/filepath"
	"time"

	"github.com/lmittmann/tint"
	slogmulti "github.com/samber/slog-multi"
	"github.com/spf13/viper"
	"gopkg.in/natefinch/lumberjack.v2"
)

var (
	LOG log
)

type log struct {
	*slog.Logger
}

// 写入默认配置
func (l *log) dc() {
	viper.SetDefault("log.console.level", "DEBUG")
	viper.SetDefault("log.file.level", "DEBUG")
	viper.SetDefault("log.file.path", "logs")
}

func (l *log) setup() {
	ch := consoleHandler()
	fh := fileHandler()
	logger := slog.New(slogmulti.Fanout(ch, fh))
	slog.SetDefault(logger)
	l.Logger = logger
}

// console handle
func consoleHandler() slog.Handler {
	var level slog.Level
	err := level.UnmarshalText([]byte(viper.GetString("log.console.level")))
	if err != nil {
		panic(err)
	}

	return tint.NewHandler(os.Stdout, &tint.Options{
		Level:      level,
		TimeFormat: time.Kitchen,
	})
}

// file handle
func fileHandler() slog.Handler {
	var level slog.Level
	szPath := viper.GetString("log.file.path")
	err := level.UnmarshalText([]byte(viper.GetString("log.file.level")))
	if err != nil {
		panic(err)
	}

	fn := filepath.Join(szPath, "track.log")
	lumberjackLogger := &lumberjack.Logger{
		Filename:   fn,
		MaxSize:    viper.GetInt("maxSize"),
		MaxBackups: viper.GetInt("maxBackups"),
		MaxAge:     viper.GetInt("maxAge"),
		Compress:   false,
	}

	return slog.NewJSONHandler(lumberjackLogger, &slog.HandlerOptions{Level: level})
}
